import math
import time
import padocr
import operation

def navigate_to_target(
        current_pos: tuple[float, float],
        target_pos: tuple[float, float],
        device_serial: str,
        joystick_center: tuple[int, int] = (281, 606),
        joystick_radius: int = 150,
        move_threshold: int = 2,
        adb_path: str = r"C:\platform-tools\adb.exe"
) -> bool:
    """
    使用ADB控制角色移动到目标位置

    参数:
        current_pos: 当前坐标 (x, y)
        target_pos: 目标坐标 (x, y)
        device_serial: 设备序列号
        joystick_center: 轮盘中心坐标 (默认: 281,606)
        joystick_radius: 轮盘半径 (默认: 150)
        move_threshold: 停止移动的阈值距离 (默认: 10像素)
        adb_path: adb路径 (默认: 雷电模拟器路径)

    返回:
        bool: 是否到达目标附近
    """
    # 计算方向向量
    dx = target_pos[0] - current_pos[0]
    dy = target_pos[1] - current_pos[1]
    distance = math.sqrt(dx ** 2 + dy ** 2)

    # 如果已经在目标附近，释放轮盘并返回
    if distance <= move_threshold:
        _adb_swipe(joystick_center, joystick_center, device_serial, adb_path)
        return True

    # 计算方向角度(0-360度)
    angle = math.degrees(math.atan2(-dy, dx)) % 360

    # 计算移动力度(0.1-1.0)
    power = min(1.0, max(0.1, distance / 200))

    # 计算轮盘目标位置
    angle_rad = math.radians(angle)
    end_x = joystick_center[0] + joystick_radius * power * math.cos(angle_rad)
    end_y = joystick_center[1] - joystick_radius * power * math.sin(angle_rad)  # Y轴取反

    # 发送ADB滑动命令模拟轮盘操作
    _adb_swipe(joystick_center, (int(end_x), int(end_y)), device_serial, adb_path)

    return False


def _adb_swipe(
        start_pos: tuple[int, int],
        end_pos: tuple[int, int],
        device_serial: str,
        adb_path: str,
        duration_ms: int = 100
) -> bool:
    """
    内部函数: 执行ADB滑动命令

    参数:
        start_pos: 起始位置 (x, y)
        end_pos: 结束位置 (x, y)
        device_serial: 设备序列号
        adb_path: adb路径
        duration_ms: 滑动持续时间(毫秒)

    返回:
        bool: 命令是否执行成功
    """
    import subprocess

    cmd = [
        adb_path,
        '-s', device_serial,
        'shell', 'input', 'swipe',
        str(start_pos[0]), str(start_pos[1]),
        str(end_pos[0]), str(end_pos[1]),
        str(duration_ms)
    ]

    try:
        subprocess.run(cmd, check=True, timeout=2)
        return True
    except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
        return False


def calculate_direction(start_pos: tuple[float, float], target_pos: tuple[float, float]) -> tuple[float, float]:
    """
    计算从起点到目标点的方向和距离

    参数:
        start_pos: 起始坐标 (x, y)
        target_pos: 目标坐标 (x, y)

    返回:
        tuple: (角度, 距离)
    """
    dx = target_pos[0] - start_pos[0]
    dy = target_pos[1] - start_pos[1]
    distance = math.sqrt(dx ** 2 + dy ** 2)
    angle = math.degrees(math.atan2(-dy, dx)) % 360  # Y轴取反，转换为0-360度

    return angle, distance


def auto_navigate(
        target_pos: tuple[int, int],
        device_serial: str,
        max_attempts: int = 50,
        check_interval: float = 0.5,
        adb_path: str = r"D:\leidian\LDPlayer9\adb.exe"
) -> bool:
    """
    自动导航到目标位置（完整流程）

    参数:
        target_pos: 目标坐标 (x, y)
        device_serial: 设备序列号
        max_attempts: 最大尝试次数
        check_interval: 位置检查间隔(秒)
        adb_path: adb路径

    返回:
        bool: 是否成功到达目标
    """
    for attempt in range(max_attempts):
        try:
            # 1. 获取当前位置
            current_pos = padocr.get_current_position(device_serial=device_serial)
            print(f"当前位置: {current_pos}")

            # 2. 导航到目标
            reached = navigate_to_target(
                current_pos,
                target_pos,
                device_serial,
                adb_path=adb_path
            )

            if reached:
                print("成功到达目标位置！")
                return True

            # 3. 等待下次检查
            time.sleep(check_interval)

        except Exception as e:
            print(f"导航出错: {str(e)}")
            time.sleep(1)  # 出错后等待更长时间

    print("达到最大尝试次数仍未到达目标")
    return False

if __name__ == '__main__':
    client = operation.connect_emulator()
    devices = client.devices()

    if not devices:
        print("没有找到连接的设备")
        exit()

    # 打印所有设备信息
    print("可用设备:")
    for i, device in enumerate(devices):
        print(f"{i}: {device.serial}")

    # 自动选择第一个设备（或让用户选择）
    selected_device = devices[0]
    TARGET_POSITION = (338, 333)  # 目标坐标

    # 执行自动导航
    auto_navigate(
        target_pos=TARGET_POSITION,
        device_serial=selected_device.serial,
        max_attempts=30,
        check_interval=0.1
    )
